package com.ztrue.framework.core.domain.impl;

import com.ztrue.framework.core.domain.IAggregateRoot;
import com.ztrue.framework.core.domain.IAggregateRootCache;
import com.ztrue.framework.core.domain.IAggregateStorage;
import com.ztrue.framework.core.domain.IRepository;
import com.ztrue.framework.exception.ArgumentNullException;
import com.ztrue.common.utilities.StringUtil;

/**
 * 默认的聚合跟存储库
 *
 * @author zhangw
 * @date 2016/11/2 16:06
 * @version: 1.0
 */
public class DefaultRepository implements IRepository {
    private IAggregateRootCache aggregateRootCache;
    private IAggregateStorage aggregateStorage;

    public DefaultRepository(IAggregateRootCache aggregateRootCache, IAggregateStorage aggregateStorage) {
        this.aggregateRootCache = aggregateRootCache;
        this.aggregateStorage = aggregateStorage;
    }

    /**
     * 根据聚合根ID获取聚合根
     *
     * @param aggregateRootId
     * @return
     */
    @Override
    public <T extends IAggregateRoot> T get(String aggregateRootId, Class<T> cls) {
        if (StringUtil.isEmpty(aggregateRootId)) throw new ArgumentNullException("聚合根ID不可为空");
        if (cls == null) throw new ArgumentNullException("聚合根类型不可为空");
        T aggregateRoot = aggregateRootCache.<T>get(aggregateRootId);
        if (aggregateRoot == null) {
            aggregateRoot = aggregateStorage.get(aggregateRootId, cls);
        }
        if (aggregateRoot != null) {
            aggregateRootCache.set(aggregateRoot);
        }
        return aggregateRoot;
    }
}
